const mongoose = require('mongoose')

const commentSchema = new mongoose.Schema({
  text: {
    type: String,
    required: [true, '评论内容是必需的'],
    trim: true,
    minlength: [1, '评论内容不能为空'],
    maxlength: [1000, '评论内容不能超过1000个字符']
  },
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true
  },
  targetType: {
    type: String,
    enum: ['video', 'post'],
    required: true
  },
  targetId: {
    type: mongoose.Schema.Types.ObjectId,
    required: true,
    refPath: 'targetType'
  },
  parentId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Comment',
    default: null
  },
  replies: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Comment'
  }],
  likes: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  }],
  dislikes: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  }],
  isEdited: {
    type: Boolean,
    default: false
  },
  status: {
    type: String,
    enum: ['active', 'hidden', 'deleted'],
    default: 'active'
  }
}, {
  timestamps: true
})

// 获取评论统计信息
commentSchema.methods.getStats = function() {
  return {
    likes: this.likes.length,
    dislikes: this.dislikes.length,
    replies: this.replies.length
  }
}

// 检查用户是否已点赞
commentSchema.methods.isLikedBy = function(userId) {
  return this.likes.includes(userId)
}

// 检查用户是否已点踩
commentSchema.methods.isDislikedBy = function(userId) {
  return this.dislikes.includes(userId)
}

// 处理点赞
commentSchema.methods.toggleLike = async function(userId) {
  const isLiked = this.likes.includes(userId)
  const isDisliked = this.dislikes.includes(userId)
  
  if (isLiked) {
    // 取消点赞
    this.likes = this.likes.filter(id => !id.equals(userId))
  } else {
    // 添加点赞
    this.likes.push(userId)
    // 如果已经点踩，则移除点踩
    if (isDisliked) {
      this.dislikes = this.dislikes.filter(id => !id.equals(userId))
    }
  }
  
  return this.save()
}

// 处理点踩
commentSchema.methods.toggleDislike = async function(userId) {
  const isDisliked = this.dislikes.includes(userId)
  const isLiked = this.likes.includes(userId)
  
  if (isDisliked) {
    // 取消点踩
    this.dislikes = this.dislikes.filter(id => !id.equals(userId))
  } else {
    // 添加点踩
    this.dislikes.push(userId)
    // 如果已经点赞，则移除点赞
    if (isLiked) {
      this.likes = this.likes.filter(id => !id.equals(userId))
    }
  }
  
  return this.save()
}

// 添加回复
commentSchema.methods.addReply = async function(replyId) {
  if (!this.replies.includes(replyId)) {
    this.replies.push(replyId)
    await this.save()
  }
  return this
}

// 软删除评论
commentSchema.methods.softDelete = async function() {
  this.status = 'deleted'
  return this.save()
}

// 隐藏评论
commentSchema.methods.hide = async function() {
  this.status = 'hidden'
  return this.save()
}

// 恢复评论
commentSchema.methods.restore = async function() {
  this.status = 'active'
  return this.save()
}

// 获取视频的评论列表
commentSchema.statics.getVideoComments = async function(videoId, page = 1, limit = 20) {
  const skip = (page - 1) * limit
  
  return this.find({
    video: videoId,
    parent: null,  // 只获取顶级评论
    status: 'active'
  })
    .sort({ createdAt: -1 })
    .skip(skip)
    .limit(limit)
    .populate('user', 'username avatar')
    .populate({
      path: 'replies',
      match: { status: 'active' },
      populate: { path: 'user', select: 'username avatar' }
    })
}

// 获取评论的回复列表
commentSchema.statics.getReplies = async function(commentId, page = 1, limit = 10) {
  const skip = (page - 1) * limit
  
  return this.find({
    parent: commentId,
    status: 'active'
  })
    .sort({ createdAt: 1 })
    .skip(skip)
    .limit(limit)
    .populate('user', 'username avatar')
}

const Comment = mongoose.model('Comment', commentSchema)

module.exports = Comment